import '../entity/game.dart';
import '../entity/product.dart';
import 'database_helper.dart';

class GameRepository {
  final dbHelper = DatabaseHelper.instance;

  //插入新游戏
  Future<void> insert(Game game) async {
    final db = await dbHelper.database;
    await db.insert('games', game.toMap());
  }

  //获取所有游戏
  Future<List<Game>> getAllGames() async {
    final db = await dbHelper.database;
    final List<Map<String, dynamic>> maps = await db.query('games');
    return List.generate(maps.length, (i) => Game.fromMap(maps[i]));
  }

  //获取带有可购买项的游戏
  Future<List<Game>> getAllGamesWithProducts() async {
    final db = await dbHelper.database;

    //一次性获取所有游戏
    final List<Map<String, dynamic>> gameMaps = await db.query('games');
    if (gameMaps.isEmpty) {
      return [];
    }

    //一次性获取所有产品
    final List<Map<String, dynamic>> productMaps = await db.query('products');
    final allProducts = productMaps.map((map) => Product.fromMap(map)).toList();

    //在内存中将产品按 gameId 分组，方便查找
    final Map<String, List<Product>> productsByGameId = {};
    for (final product in allProducts) {
      // 如果Map中还没有这个gameId的键，就创建一个空列表
      (productsByGameId[product.gameId] ??= []).add(product);
    }

    //组合游戏和其对应的产品列表
    final List<Game> gamesWithProducts = [];
    for (final gameMap in gameMaps) {
      final game = Game.fromMap(gameMap);
      final productsForThisGame = productsByGameId[game.id] ?? [];
      gamesWithProducts.add(game.copyWith(products: productsForThisGame));
    }

    return gamesWithProducts;
  }

  //获取单个游戏，并附带其所有产品列表
  Future<Game?> getGameWithProducts(String gameId) async {
    final db = await dbHelper.database;

    //获取游戏本体信息
    final gameMaps = await db.query('games', where: 'id = ?', whereArgs: [gameId]);
    if (gameMaps.isEmpty) return null;

    final game = Game.fromMap(gameMaps.first);

    //获取该游戏的所有产品
    final productMaps = await db.query('products', where: 'gameId = ?', whereArgs: [gameId]);
    final products = productMaps.map((map) => Product.fromMap(map)).toList();

    //使用copyWith组合游戏和其产品列表
    return game.copyWith(products: products);
  }
}